package com.desire.redis;


import cn.hutool.core.util.StrUtil;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.ValueOperations;

import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@SpringBootTest
public class Redis_DecrBy {
    @Resource(name = "redisTemplate")
    private ValueOperations<String, Integer> valueOperations;

    @Test
    void tt() throws InterruptedException {
        String key = "product#01";
        valueOperations.set(key, 5);
        // 创建线程池
        ExecutorService executorService = Executors.newCachedThreadPool();

        for (int i = 0; i < 10; i++) {
            executorService.execute(() -> {
                // 获取 key：product#01 的值  5
                Integer value = valueOperations.get(key);
                if (value >= 1) {
                    // 若大于 1 则 进行 重新赋值 -1
                    valueOperations.set(key, value - 1);
                    System.out.println(StrUtil.format("Thread {} -> succeed", Thread.currentThread().getName()));
                } else {
                    System.out.println(StrUtil.format("Thread {} -> fail", Thread.currentThread().getName()));
                }
            });
        }
        Thread.sleep(10 * 1000);
    }

    @Test
    void decBy() throws InterruptedException {
        String key = "student#02";
        valueOperations.set(key, 5);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            executorService.execute(() -> {
                Long value = valueOperations.decrement(key);
                if (value >= 0) {
                    System.out.println(StrUtil.format("Thread {} -> succeed,shengyukucun{}", Thread.currentThread().getName(), value));
                } else {
                    System.out.println(StrUtil.format("Thread {} -> fail", Thread.currentThread().getName()));
                }
            });
        }
        Thread.sleep(10 * 1000);
    }

}
